from . import api
from flask import request, jsonify, current_app
from myapp.models import get_conn, ImageTable
import datetime
import time

db_session = get_conn()

@api.route("/upload", methods=["POST"])
def upload_file():

    image_tb = ImageTable.image_tb
    file = request.files.get("upload_file")
    file_name = request.form.get("file_name")
    if not file:
        return jsonify(status_code=302, msg="未知参数值或参数值不合法！")
    sub_file = file.filename.split(".")

    if not file_name:
        file_name = "".join(sub_file[:-1])
    rename_file = str(int(time.time())) + "." + sub_file[-1]

    if sub_file[-1] not in ['jpg', 'png', 'gif', 'bmp', 'jpeg', 'JPG', 'PNG','BMP', 'JPEG']:
        return jsonify(status_code=400, msg="图片格式非法，请检查后再重试...")


    file_path =  "static/" + rename_file
    file_url = request.url_root + "api/v1.0/file/" + rename_file
    file.save(file_path)
    data_dict = {
        
        "image_name":file_name,
        "image_url":file_url,
        "pub_time":datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "author":"测试"
    }
    try:
        r = db_session.execute(image_tb.insert().values(data_dict))
        data_dict["id"] = r.lastrowid
        db_session.commit()
    except Exception as e:
        current_app.logger.error("服务器异常，异常信息：{}".format(e))
        return jsonify(status_code=400, msg="服务器异常，异常信息：{}".format(e))

    return jsonify(status_code=200, msg=data_dict)